<script setup lang="ts">
import { RouterLink, RouterView, useRoute, onBeforeRouteUpdate  } from 'vue-router'
import useChatStore from '@/stores/chatStore'
import useRoomStore from '@/stores/roomStore'
import useFriendStore from '@/stores/friendStore'
import { onMounted, ref, nextTick } from 'vue'
import moment from 'moment'
import { setSessionItem, getSessionItem } from '@/utils/SessionStrageUtils.ts'
import pubsub from 'pubsub-js'
import CommentList from './views/CommentList.vue'
import notifyVolice from '@/assets/mp4/notification-sound.wav'

// 获取聊天记录以及聊天房间数据

const renderDom = ref<Boolean>(false)
const chatStore = useChatStore()
const roomStore = useRoomStore()
const friendStore = useFriendStore()

// 新消息
const addMessage = (obj: any) => {
  debugger
  Object.assign(obj, {
    messageId: obj.id,
    id: 0,
    img: obj.img,
    sendUserName: obj.sendUserName,
    type: parseInt(obj.type),
    time: moment(new Date(obj.createTime)).format('YYYY-MM-DD HH:mm:ss'),
    status: 1
  })
  // 添加消息到消息列表
  chatStore.sendMessageObj(obj, obj.roomId.toString())
  // 设置房间未读数量
  roomStore.setRoomNoReadCount(obj.roomId.toString())
}
const playNewMessage = () => {
  // 播放声音
  const audio = new Audio(notifyVolice);
  audio.play();     
}
onMounted(()=> {
  const url = window.location.href
  const route = useRoute()
  const renderDomValue = Boolean(getSessionItem('renderDom'))
  renderDom.value =  renderDomValue
  // if(url.indexOf("home") > -1) {
  //   chatStore.initChatData()
  // }
  window.api.on('main-load-records', (eventA: any, msg: any) =>{
    chatStore.initChatData()
  })
  // Socket接收消息
  window.api.on('websocket-message', (eventA: any, msg: any) => {
    // 判断消息类型 onlineCall || message
    const msgObj = JSON.parse(msg)
    let obj = msgObj.data
    switch (msgObj.type) {
      case 'onlineCall': // 在线通话
        roomStore.setTheLatestMessageByRoomId(msgObj.roomId, msgObj)
        break;
      case 'message': { // 普通消息
        playNewMessage()
        addMessage(obj)
        break;
      }
      case 'friendRequest': // 好友请求
        playNewMessage()
        friendStore.addFriendRequest(obj)
        break;
      case 'newFriend': // 好友请求通过
        playNewMessage()
        // 插入聊天房间
        roomStore.addChatRoomWithMessage(obj.room, obj.message)
        // 插入好友关系
        friendStore.addFriendsRelation(obj.relation)
        break;  
      default:
        break;
    }
    //chatStore.setTheLatestMessageByRoomId(msg.roomId, msg)
  }); 
  // 添加好友的信息
  window.api.on('main-request-friends', (eventA: any, msg: any) => {
    pubsub.publish('add-friends', msg)
  }); 
})
</script>

<template>
    <RouterView />
</template>

<style scoped></style>
